import { LoginService } from '../../services/login.service';
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { UserService } from '../../services/user.service';
import { ExceptionHandler } from '../../handler/exception.handler';
import { CoreService } from '../../services/core.service';
import { Account } from 'src/app/models';
import { AuthorityService } from 'src/app/common/authority/authority.service';

@Component({
  selector: 'zepride-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
  validateForm!: FormGroup;
  username: string;
  password: string;

  logining = false;
  orgId = '';
  verifyCode = {
    id: '',
    code: ''
  };

  loginPageConfig = {
    orgId: '',
    page: {
      extends: {
        backgroundColor: '#1780A3',
        backgroundImage: '../../../assets/images/img_png_01.png',
        logoUrl: '../../../assets/images/logo.png',
        headUrl: '../../../assets/images/logo_min.png',
        bottomImageList: [
          '../../../assets/images/img_01.png',
          '../../../assets/images/img_02.png',
          '../../../assets/images/img_03.png',
          '../../../assets/images/img_04.png'
        ]
      }
    }
  };

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private loginService: LoginService,
    private userService: UserService,
    private msg: NzMessageService,
    private coreSvr: CoreService
  ) {
    this.route.queryParams.subscribe(queryParams => {
      this.orgId = queryParams.orgId;
      if (!this.orgId) {
        this.orgId = localStorage.getItem('orgid');
      }
      this.loginService.orgid = this.orgId;
    });
  }
  async ngOnInit() {
    this.validateForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      code: [null]
    });

    this.loginPageConfig.orgId = localStorage.getItem('orgid');

    this.getVerifyCode();
    await this.getLoginPageConifg();
  }

  entersearch() {
    const event = window.event || arguments.callee.caller.arguments[0];
    if (event.keyCode == 13) {
      this.confirm();
    }
  }
  async confirm() {
    if (!this.validateForm.valid) {
      return;
    }
    if (this.logining) {
      return;
    }
    this.logining = true;
    const params = {
      username: this.username,
      password: this.password,
      orgId: this.orgId,
      verifyCode: {
        id: this.verifyCode.id,
        code: this.validateForm.controls.code.value
      }
    };
    try {
      const data = await this.loginService.login(params);
      this.loginSuccess(data);
    } catch (error) {
      ExceptionHandler.current.handleError(error);
      await this.getVerifyCode();
    } finally {
      this.logining = false;
    }
  }

  loginSuccess(data) {
    this.loginService.token = data.token.value;
    this.userService.user = data.user;
    this.userService.account = data.account;
    this.msg.success('登录成功');
    this.router.navigateByUrl('home');
  }

  private async getLoginPageConifg() {
    try {
      const config = await this.coreSvr.getLoginPageConfig(this.orgId);
      const loginPageConfig = config;
      if (loginPageConfig && loginPageConfig.extends) {
        this.loginPageConfig.page.extends = loginPageConfig.extends;
      }
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  async getVerifyCode() {
    this.verifyCode = await this.loginService.getVerifyCode();
  }

  submitForm(): void {
    // tslint:disable-next-line: forin
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
  }

  forgetPassword() {
    this.msg.error('如果您忘记密码，请联系贵单位系统管理员');
  }

}
